package com.sdry.approval.controller;

import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @program: info_sdry
 * @description: 上传文件
 * @author: cb
 * @create: 2020-02-21 14:38
 **/
@Controller
public class UploadController {

    @RequestMapping(value = "/upload")
    @ResponseBody
    public String upload(MultipartFile file, HttpServletRequest request, HttpSession session) throws IOException {
        JSONObject json = new JSONObject();
        // 原始名称
        String originalFilename = file.getOriginalFilename();
        if (file != null && originalFilename != null && originalFilename.length() > 0) {
            //获取后缀名
            String sufixName = originalFilename.substring(originalFilename.indexOf("."));
            //重命名
            String newName = UUID.randomUUID() + sufixName;
            //设置文件上传的目录
            String picPath="D:\\imgUpload\\";
            File filePath=new File(picPath);
            //如果保存文件的地址不存在，就先创建目录
            if(!filePath.exists()){
                filePath.mkdirs();
            }

            // 新图片
            File newFile = new File(picPath+newName);
            // 将内存中的数据写入磁盘
            file.transferTo(newFile);

            session=request.getSession();


            json.put("code", 0);
            json.put("face", "D:\\imgUpload\\" + newName);
            System.out.println(json.toString());
            return json.toString();
        }
        json.put("code", 1);
        System.out.println(json.toString());
        return json.toString();
    }

}
